package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"h1/utils"
	"time"
)

type Scene struct {
	Id              int64     `orm:"pk;auto"`   // 项目ID  id
	SceneId         int64     `orm:"size(11)"`  //场景ID scene_id
	Title           string    `orm:"size(255)"` // 场景名称
	IconName        string    `orm:"size(255)"` // 场景icon
	Participant     string    `orm:"size(255)"` // 参与者
	CoverImageId    int64     `orm:"size(11)"`  //封面图片ID
	CoverImageThumb string    `orm:"size(255)"` // 封面图缩略图
	CoverImagePath  string    `orm:"size(255)"` // 封面图原图路径
	ParentId        int64     `orm:"size(11)"`  //场景父级ID
	Defect          string    `orm:"size(255)"` //
	Advance         string    `orm:"size(255)"` // 场景优点
	Describe        string    `orm:"size(255)"` // 场景描述
	Author          string    `orm:"size(255)"` // 场景作者
	CheckLog        string    `orm:"size(255)"` // 备注
	CheckStatus     int64     `orm:"size(1)"`   // 0:未提交审核，1：审核中；2：审核通过；3：审核失败
	VersionStatus   int64     `orm:"size(1)"`   // 0:草稿箱版本;1：历史版本；2：当前版本
	Version         string    `orm:"size(255)"` // v1.1.1
	Pv              int64     `orm:"size(11)"`  // 场景浏览量
	CreateAt        time.Time `orm:"auto_now_add;type(datetime)"form:"-"`
	CreateBy        int64     `orm:"size(11)"` //用户名称
	UpdateAt        time.Time `orm:"auto_now;type(datetime)"`
	UpdateName      string    `orm:"size(20)"` //
	CreateName      string    `orm:"size(20)"` //更新者姓名
	UpdateBy        int64     `orm:"size(11)"` //更新者姓名
	ShowElement     int64     `orm:"size(1)"`
	ShowAdvance     int64     `orm:"size(1)"`
	ShowDescribe    int64     `orm:"size(1)"`
	ShowImage       int64     `orm:"size(1)"`
	ShowVideo       int64     `orm:"size(1)"`
	ShowScene       int64     `orm:"size(1)"`
	ShowDefect      int64     `orm:"size(1)"`
	DefaultEditBy   string    `orm:"size(255)"`
	EditBy          string    `orm:"size(255)"`
	EditFlag        int64     `orm:"size(1)"`
	SubmitLog       string    `orm:"size(255)"`
}

// 获取模型表名
func (m *Scene) TableName() string {
	return "scene"
}

// 获取全部用户
func (m *Scene) GetAllUser() []*Scene {
	info := Scene{}
	list := make([]*Scene, 0)
	_, _ = info.Query().All(&list)
	return list
}

// 查询方法
func (m *Scene) Query() orm.QuerySeter {
	return orm.NewOrm().QueryTable(m)
}

// 添加用户
func (m *Scene) Insert() error {
	_, err := orm.NewOrm().Insert(m)
	return err
}

// 删除用户
func (m *Scene) Delete() error {
	_, err := orm.NewOrm().Delete(m)
	return err
}

// 修改用户信息
func (m *Scene) Update(fields ...string) error {
	_, err := orm.NewOrm().Update(m, fields...)
	return err
}
func (m *Scene) Read(fields ...string) (int64, error) {
	if err := orm.NewOrm().Read(m, fields...); err != nil {
		return 0, err
	}
	return m.Id, nil
}

// 通过ID查询单个用户信息
func (m *Scene) GetInfoById(uid int64) (*Scene, error) {
	err := m.Query().Filter("id", uid).One(m)
	return m, err
}
func (m *Scene) GetObjectById(uid int64) (*Scene, error) {
	//err := m.Query().Filter("id", uid).Filter("check_status", 2).One(m)
	err := m.Query().Filter("id", uid).One(m)
	return m, err
}
func (m *Scene) GetEleParentListsByParentId(uid int64) []map[string]interface{} {
	list := make([]*Scene, 0)
	_, _ = m.Query().Filter("parent_id", uid).Filter("check_status", 2).All(&list)
	resTree := make([]map[string]interface{}, 0)
	for _, citem := range list {
		cres := SceneLibsJson(citem)
		resTree = append(resTree, cres)
	}
	return resTree
}

func (m *Scene) GetParentById(uid int64) (*Scene, error) {
	//err := m.Query().Filter("id", uid).Filter("check_status", 2).One(m)
	err := m.Query().Filter("parent_id", uid).One(m)
	return m, err
}

// 获取用户总数
func (m *Scene) GetSceneCounts() int64 {
	qs := orm.NewOrm().QueryTable(m)
	count, _ := qs.Filter("check_status", 2).Count()
	return count
}

// 获取每天的用户数
func (m *Scene) GetScenePerDayCounts(string2 string) int64 {
	strMin := string2 + " 00:00:00"
	strMax := string2 + " 23:59:59"
	fmt.Println("-----------------", strMin, strMax)
	qs := orm.NewOrm().QueryTable(m)
	cnt, _ := qs.Filter("check_status", 2).Filter("create_at__gte", strMin).Filter("create_at__lte", strMax).Count()
	return cnt
}

// 获取每天区间的用户数
func (m *Scene) GetSceneRandDayCounts(old string, new string) int64 {
	strMin := old + " 00:00:00"
	strMax := new + " 23:59:59"
	fmt.Println("-----------------", strMin, strMax)
	qs := orm.NewOrm().QueryTable(m)
	cnt, _ := qs.Filter("check_status", 2).Filter("create_at__gte", strMin).Filter("create_at__lte", strMax).Count()
	return cnt
}

// 通过父节点获取project
func (m *Scene) GetObjectListByParentId(uid int64, check int64) []*Scene {
	list := make([]*Scene, 0)
	_, _ = m.Query().Filter("parent_id", uid).Filter("check_status", check).All(&list)
	return list
}

// 通过父节点获取project
func (m *Scene) GetObjectListByGTParentId(uid int64, check int64) []*Scene {
	list := make([]*Scene, 0)
	_, _ = m.Query().Filter("parent_id__gt", uid).Filter("check_status", check).All(&list)
	return list
}

func GetAllSceneLst(uid int64) map[string]interface{} {

	resDic := utils.MakeJson()
	//我创建的
	sqls_1 := "SELECT  *  from tb_scene WHERE 1 > 0 and check_status != 0 and create_by = " + utils.Int64ToString(uid)
	maps_1, _ := MutiJoinTableQuery(sqls_1)
	resDic["myCreateArr"] = productUserList(maps_1)
	////我修改的
	//sqls_2 := "SELECT  *  from tb_scene WHERE 1 > 0 and check_status != 0 and update_by = " + utils.Int64ToString(uid) + ""
	//maps_2, _:= MutiJoinTableQuery(sqls_2)
	//resDic["myEeditArr"] = productUserList(maps_2)
	// 允许我修改的
	sqls_3 := "SELECT  *  from tb_scene WHERE 1 > 0  and create_by !=" + utils.Int64ToString(uid) + " and edit_by  like '%" + utils.Int64ToString(uid) + "%'"
	maps_3, _ := MutiJoinTableQuery(sqls_3)
	resDic["editByMeArr"] = productUserList(maps_3)
	// 所有的
	sqls_4 := "SELECT  *  from tb_scene WHERE 1 > 0 "
	maps_4, _ := MutiJoinTableQuery(sqls_4)
	resDic["allArr"] = productUserList(maps_4)
	// 我保存的
	sqls_5 := "SELECT  *  from tb_scene WHERE 1 > 0 and create_by =" + utils.Int64ToString(uid) + " and check_status = 0"
	maps_5, _ := MutiJoinTableQuery(sqls_5)
	resDic["mySaveArr"] = productUserList(maps_5)

	return resDic
}

func productUserList(maps []orm.Params) []map[string]interface{} {
	resArr := utils.MakeDicArray()
	for _, item := range maps {
		projectID := item["id"]
		csql := "SELECT b.* FROM tb_project_scene a, tb_scene b WHERE a.scene_id=b.id and a.project_id =  " + projectID.(string)
		counts, _ := MutiJoinTableQuery(csql)
		item["sceneArr"] = counts
		item["scene_num"] = len(counts)
		//统计
		edit_by := item["edit_by"]
		var sql = ""
		//格式化为数组
		editArr := utils.StringToArrayByStr(edit_by.(string))
		// 拼接sql语句
		for _, st := range editArr {
			sql += " or tb_user.id = " + st
		}
		sqls := "SELECT  *  from tb_user WHERE 1 < 0 " + sql
		userList, _ := MutiJoinTableQuery(sqls)
		//temp := SceneLibsJson(item)
		item["roleArr"] = userList
		item["person_num"] = len(userList)
		resArr = append(resArr, item)
	}
	return resArr
}
